package com.example.erp.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.erp.entity.Type;
import com.example.erp.entity.dto.ExcelDto;
import com.example.erp.mapper.TypeMapper;
import com.example.erp.service.ITypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 类型 服务实现类
 * </p>
 *
 * @author rws
 * @since 2025-01-08
 */
@Service
public class TypeServiceImpl extends ServiceImpl<TypeMapper, Type> implements ITypeService {

    @Autowired
    private TypeMapper typeMapper;

    @Override
    public void insertType(List<ExcelDto> excelDtoList) {

        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String time = now.format(formatter);





        for(ExcelDto excelDto:excelDtoList){
            QueryWrapper<Type> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("name", excelDto.getLevel1Name());
            Type type =typeMapper.selectOne(queryWrapper);
            if(type==null){
                Type newtype=new Type();
                newtype.setName(excelDto.getLevel1Name())
                        .setTypeLevel(1)
                        .setCreateBy(StpUtil.getLoginIdAsInt())
                        .setUpdateBy(StpUtil.getLoginIdAsInt())
                        .setCreateTime(time)
                        .setUpdateTime(time);
                typeMapper.insert(newtype);
            }
        }

        for(ExcelDto excelDto:excelDtoList){
            if(excelDto.getLevel2Name().equals(""))continue;
            QueryWrapper<Type> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("name", excelDto.getLevel2Name());
            Type type =typeMapper.selectOne(queryWrapper);

            QueryWrapper<Type> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.eq("name", excelDto.getLevel1Name());
            int pid=typeMapper.selectOne(queryWrapper2).getTypeId();
            if(type==null){
                Type newtype=new Type();

                newtype.setName(excelDto.getLevel2Name())
                        .setTypeLevel(2)
                        .setCreateBy(StpUtil.getLoginIdAsInt())
                        .setUpdateBy(StpUtil.getLoginIdAsInt())
                        .setCreateTime(time)
                        .setUpdateTime(time)
                        .setPId(pid);
                typeMapper.insert(newtype);
            }

        }
    }
}
